import { apiClient } from './config';
import { resolveServiceURL } from "./resolve-service-url";

// 数据源接口定义
export interface DataSource {
  id: string;
  name: string;
  description: string;
  type: 'mysql' | 'oracle';
  host: string;
  port: number;
  username: string;
  database_name: string;
  schema_name?: string;
  service_name?: string;
  ssl: boolean;
  status: 'inactive' | 'active' | 'error';
  created_at: string;
  updated_at: string;
  last_connected_at?: string;
  error_message?: string;
}

export interface DataSourceCreate {
  name: string;
  description?: string;
  type: 'mysql' | 'oracle';
  host: string;
  port: number;
  username: string;
  password: string;
  database_name: string;
  schema_name?: string;
  service_name?: string;
  ssl?: boolean;
  ssl_ca?: string;
  ssl_cert?: string;
  ssl_key?: string;
}

export interface DataSourceUpdate {
  name?: string;
  description?: string;
  host?: string;
  port?: number;
  username?: string;
  password?: string;
  database_name?: string;
  schema_name?: string;
  service_name?: string;
  ssl?: boolean;
  ssl_ca?: string;
  ssl_cert?: string;
  ssl_key?: string;
}

export interface ConnectionTestResponse {
  success: boolean;
  message: string;
  details: Record<string, any>;
}

export interface Table {
  name: string;
  description?: string;
}

export interface Column {
  // 原始格式字段
  column_name?: string;
  data_type?: string;
  is_nullable?: string;
  column_key?: string;
  column_default?: any;
  extra?: string;
  column_comment?: string;
  character_maximum_length?: number;
  numeric_precision?: number;
  numeric_scale?: number;
  
  // 优化格式字段
  name?: string;
  type?: string;
  nullable?: string;
  default?: any;
  comment?: string;
  max_length?: number;
  precision?: number;
  scale?: number;
}

export interface TablesResponse {
  success: boolean;
  tables: Table[];
  count: number;
  schema?: string;
  message?: string;
}

export interface ColumnsResponse {
  success: boolean;
  table_name: string;
  columns: Column[];
  count: number;
  schema?: string;
  message?: string;
}

// 元数据相关接口定义
export interface TableMetadata {
  table_name: string;
  schema?: string;
  type: 'table' | 'view';
  table_comment?: string;
  comment?: string;           // 优化格式中的注释字段
  rows_count?: number;
  size_mb?: number;
  created_at?: string;
  updated_at?: string;
  columns?: Column[];
  indexes?: Index[];          // 原始格式
  key_indexes?: KeyIndex[];   // 优化格式
  constraints?: Constraint[]; // 原始格式
  foreign_keys?: ForeignKey[]; // 优化格式
  sql_hints?: string[];       // 优化格式中的SQL提示
  sample_data?: any[];        // 优化格式中的样本数据
}

export interface Index {
  index_name: string;
  index_type: string;
  columns?: string[];
  unique: boolean;
  index_comment?: string;
}

export interface Constraint {
  constraint_name: string;
  constraint_type: string;
  columns?: string[];
  referenced_table?: string;
  referenced_columns?: string[];
  constraint_comment?: string;
}

// 优化格式的索引接口
export interface KeyIndex {
  name: string;
  type: 'primary' | 'unique';
  columns: string[];
}

// 优化格式的外键接口
export interface ForeignKey {
  columns: string[];
  references: {
    table: string;
    columns: string[];
  };
}

export interface DatabaseMetadata {
  database_name?: string;  // 原始格式
  database?: string;       // 优化格式
  charset?: string;
  collation?: string;
  size_mb?: number;
  tables_count?: number;   // 原始格式
  table_count?: number;    // 优化格式
  views_count?: number;
  created_at?: string;
  tables: TableMetadata[];
  relationships?: any[];   // 优化格式中的关系信息
}

export interface MetadataResponse {
  success: boolean;
  data: DatabaseMetadata;
  sync_time: string;
  version: string;
  message?: string;
}

// 向量化相关接口
export interface VectorizeRequest {
  include_tables: boolean;
  include_columns: boolean;
  include_relationships: boolean;
  include_indexes: boolean;
  include_constraints: boolean;
}

export interface VectorizeResponse {
  success: boolean;
  vectors_count: number;
  collection_name: string;
  processing_time: number;
  message: string;
}

export interface VectorizeStatusResponse {
  success: boolean;
  status: 'idle' | 'processing' | 'completed' | 'error';
  progress: number;
  vectors_count: number;
  total_items: number;
  started_at?: string;
  completed_at?: string;
  error_message?: string;
  message: string;
}

export interface MetadataSearchRequest {
  query: string;
  datasource_ids?: string[];
  limit: number;
}

export interface MetadataSearchResult {
  content: string;
  score: number;
  datasource_id: string;
  item_type: string;
  item_name: string;
  table_name?: string;
  column_name?: string;
  raw_data: any;
}

export interface MetadataSearchResponse {
  success: boolean;
  query: string;
  results: MetadataSearchResult[];
  count: number;
  message: string;
}


// 数据源API类
export class DataSourceApi {
  private baseUrl = resolveServiceURL('/api/datasources');

  /**
   * 获取所有数据源
   */
  async getAll(): Promise<DataSource[]> {
    const response = await apiClient.get(this.baseUrl);
    return response.data;
  }

  /**
   * 根据ID获取数据源
   */
  async getById(id: string): Promise<DataSource> {
    const response = await apiClient.get(`${this.baseUrl}/${id}`);
    return response.data;
  }

  /**
   * 创建数据源
   */
  async create(data: DataSourceCreate): Promise<DataSource> {
    const response = await apiClient.post(this.baseUrl, data);
    return response.data;
  }

  /**
   * 更新数据源
   */
  async update(id: string, data: DataSourceUpdate): Promise<DataSource> {
    const response = await apiClient.put(`${this.baseUrl}/${id}`, data);
    return response.data;
  }

  /**
   * 删除数据源
   */
  async delete(id: string): Promise<void> {
    await apiClient.delete(`${this.baseUrl}/${id}`);
  }

  /**
   * 测试数据源连接
   */
  async testConnection(id: string): Promise<ConnectionTestResponse> {
    const response = await apiClient.post(`${this.baseUrl}/${id}/test`);
    return response.data;
  }

  /**
   * 使用参数测试连接（不保存）
   */
  async testConnectionParams(data: DataSourceCreate): Promise<ConnectionTestResponse> {
    const response = await apiClient.post(`${this.baseUrl}/test-connection`, data);
    return response.data;
  }

  /**
   * 获取数据源中的表列表
   */
  async getTables(id: string): Promise<TablesResponse> {
    const response = await apiClient.get(`${this.baseUrl}/${id}/tables`);
    return response.data;
  }

  /**
   * 获取指定表的列信息
   */
  async getTableColumns(id: string, tableName: string): Promise<ColumnsResponse> {
    const response = await apiClient.get(`${this.baseUrl}/${id}/tables/${tableName}/columns`);
    return response.data;
  }

  /**
   * 获取数据源元数据（实时查询）
   * @param id 数据源ID
   */
  async getMetadata(id: string): Promise<MetadataResponse> {
    const response = await apiClient.get(`${this.baseUrl}/${id}/metadata/realtime`);
    return response.data;
  }

  /**
   * 实时获取数据源元数据（强制从数据源查询）
   * 总是从数据源实时查询最新的元数据信息
   */
  async getMetadataRealtime(id: string): Promise<MetadataResponse> {
    const response = await apiClient.get(`${this.baseUrl}/${id}/metadata/realtime`);
    return response.data;
  }

  /**
   * 向量化数据源元数据
   */
  async vectorizeMetadata(id: string, request: VectorizeRequest): Promise<VectorizeResponse> {
    const response = await apiClient.post(`${this.baseUrl}/${id}/metadata/vectorize`, request);
    return response.data;
  }

  /**
   * 获取元数据向量化状态
   */
  async getVectorizeStatus(id: string): Promise<VectorizeStatusResponse> {
    const response = await apiClient.get(`${this.baseUrl}/${id}/metadata/vectorize/status`);
    return response.data;
  }

  /**
   * 删除数据源的元数据向量
   */
  async deleteMetadataVectors(id: string): Promise<{ success: boolean; message: string; deleted_count: number }> {
    const response = await apiClient.delete(`${this.baseUrl}/${id}/metadata/vectors`);
    return response.data;
  }

  /**
   * 搜索元数据向量（为text2sql提供支撑）
   */
  async searchMetadataVectors(request: MetadataSearchRequest): Promise<MetadataSearchResponse> {
    const response = await apiClient.post(`${this.baseUrl}/metadata/search`, request);
    return response.data;
  }

  /**
   * 获取元数据向量统计信息
   */
  async getVectorizeStats(id: string): Promise<{ success: boolean; stats: any; message: string }> {
    const response = await apiClient.get(`${this.baseUrl}/${id}/metadata/vectorize/stats`);
    return response.data;
  }
}

// 导出单例实例
export const dataSourceApi = new DataSourceApi(); 